package com.weaver.seconddev.api.tl.purchase_api;

/**
 * E9原始类路径:com.api.tl.purchase_api.CreatePurchaseOrderEITAction
 * JAVA替换说明文档:https://ncnb71xwgeda.feishu.cn/wiki/JLsjwxK8xiHuPIkdu0Dc27Rlnaf?from=from_copylink
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.weaver.common.base.enumeration.result.WeaResultCodeEnum;
import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.seconddev.api.tl.service.DictCommonService;
import com.weaver.seconddev.api.tl.service.SAPCommonService;
import org.apache.commons.lang3.StringUtils;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

import javax.annotation.Resource;

/**
 * 创建PurchaseOrder统一接口
 */
@org.springframework.stereotype.Service("tl_purchase_api_CreatePurchaseOrderEITAction")
public class CreatePurchaseOrderEITAction implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    public static final org.slf4j.Logger logger_af05a192 = LoggerFactory.getLogger(CreatePurchaseOrderEITAction.class);

    @Resource(name = "tl_service_SAPCommonService")
    private SAPCommonService sapCommonService;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        /* 获取requestId
 TODO 返回值:requestId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
        String requestId = requestInfo.getRequestid();
        /* 获取流程ID
 TODO 返回值:workflowId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
        String workflowId = requestInfo.getWorkflowid();
        logger_af05a192.info(String.valueOf("RequestId:" + requestId + "======Start Create EIT PO======WorkflowId:" + workflowId));
        String createPoStatus = SUCCESS;
        // 主表
        String mainTableName = requestInfo.getRequestManager().getBillTableName();
        // 采购明细表
        String purchaseDetailTableName = requestInfo.getDetailTableInfo().getDetailTable(0).getTableDBName();
        // 采购结果表
        String purchaseResultTableName = requestInfo.getDetailTableInfo().getDetailTable(1).getTableDBName();
        logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",MainTableName:" + mainTableName + ",PurchaseDetailTableName:" + purchaseDetailTableName + ",PurchaseResultTableName:" + purchaseResultTableName));
        // 获取供应商GSS代码
        Map<String, Map<String, String>> dictInfoByType = DictCommonService.getDictInfoByType("purchase");
        Map<String, String> purchaseDictMap = DictCommonService.get(dictInfoByType.get("purchase"));
        if(purchaseDictMap == null || purchaseDictMap.isEmpty()){
            return WeaResult.fail(WeaResultCodeEnum.ERROR.getCode(), "Action执行失败,purchaseDictMap is null ");
        }
        // GSS代码
        String supplierGssCode = purchaseDictMap.get("supplier_GSS_code");
        // 房屋物业GL
        String rentPropertyGlAccount = purchaseDictMap.get("rent_property_gl_account");
        List<String> supplierGssCodeList = Arrays.asList(supplierGssCode.split(","));
        List<String> rentPropertyGlAccountList = Arrays.asList(rentPropertyGlAccount.split(","));
        logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",supplierGssCodeList:" + supplierGssCodeList + ",rentPropertyGlAccountList:" + rentPropertyGlAccountList));
        // 主表SQL
       // String mainTableQuerySql = "select id,lcbh,jhdz,shr,shrlxdh,ycxgysmc,szcs,jd,gj,dh,yhxx,bz,fjsc,szdbm,cglx,ywlx from " + mainTableName + " where requestid = ?";

        String mainTableQuerySql = "SELECT "+mainTableName+".id AS id, "+mainTableName+".lcbh AS lcbh, "+mainTableName+".jhdz AS jhdz, "+mainTableName+".shr AS shr, "+mainTableName+".shrlxdh AS shrlxdh\n" +
                "\t, "+mainTableName+".ycxgysmc AS ycxgysmc, "+mainTableName+".szcs AS szcs, "+mainTableName+".jd AS jd, "+mainTableName+".gj AS gj, "+mainTableName+".dh AS dh\n" +
                "\t, "+mainTableName+".yhxx AS yhxx, "+mainTableName+".bz AS bz, "+mainTableName+".fjsc AS fjsc, "+mainTableName+".szdbm AS szdbm, "+mainTableName+".cglx AS cglx\n" +
                "\t, "+mainTableName+".ywlx AS ywlx\n" +
                "FROM (\n" +
                "\tSELECT b.*, a.requestid\n" +
                "\tFROM e10_core_business.wfc_form_data a, e10_core_business."+mainTableName+" b\n" +
                "\tWHERE a.dataid = b.form_data_id\n" +
                "\t\tAND a.delete_type = 0\n" +
                "\t\tAND a.tenant_key = 'tl2k2r96ty'\n" +
                ") "+mainTableName+"\n" +
                "WHERE "+mainTableName+".requestid = ?\n" +
                "\tAND "+mainTableName+".delete_type = 0\n" +
                "\tAND "+mainTableName+".tenant_key = 'tl2k2r96ty'";
        logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",MainTableQuerySql:" + mainTableQuerySql));
        String poolname = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(mainTableQuerySql, poolname, requestId);
        // 主表ID
        String mainId = "";
        // 流程编号
        String processNo = "";
        // 交货地址
        String deliveryAddress = "";
        // 收货人ID
        String consigneeId = "";
        // 收货人
        String consignee = "";
        // 收货人联系电话
        String consigneePhone = "";
        // 一次性供应商名称
        String oneTimeSupplierName = "";
        // 所在城市
        String city = "";
        // 街道
        String street = "";
        // 国家
        String country = "";
        // 电话
        String telephone = "";
        // 银行信息
        String bankInfo = "";
        // 币种
        String currency = "";
        // 附件ID
        String attachmentId = "";
        // 采购类型(0:FAC-房租类,1:TPE-工具装备类,2:Travel,3:AHQ-服务类,4:ICT-IT类,5:ICT-Product Development)
        String purchaseType = "";
        // 业务类型(0:固定资产类,1:成本类,2:项目类（Global）,3:项目类（CDT）)
        String businessType = "";
        RecordSet rs2 = I18nContextUtil.getBean(RecordSet.class);

        if (rs.next()) {
            mainId = Util.null2String(rs.getString("id"));
            processNo = Util.null2String(rs.getString("lcbh"));
            attachmentId = Util.null2String(rs.getString("fjsc"));
            deliveryAddress = Util.null2String(rs.getString("jhdz"));
            consigneeId = Util.null2String(rs.getString("shr"));
            consigneePhone = Util.null2String(rs.getString("shrlxdh"));
            oneTimeSupplierName = Util.null2String(rs.getString("ycxgysmc"));
            city = Util.null2String(rs.getString("szcs"));
            street = Util.null2String(rs.getString("jd"));
            country = Util.null2String(rs.getString("gj"));
            telephone = Util.null2String(rs.getString("dh"));
            bankInfo = Util.null2String(rs.getString("yhxx"));
            currency = Util.null2String(rs.getString("bz"));
            purchaseType = Util.null2String(rs.getString("cglx"));
            businessType = Util.null2String(rs.getString("ywlx"));
        }
        /**
         * 业务类型(0:固定资产类,1:成本类,2:项目类（Global）,3:项目类（CDT）)
         * 以根据采购流程业务类型来区分，如果为A则固定资产，创建PO时该字段进行赋x值，其他为空
         */
        // String grNonValued = "";
        // if (StringUtils.isNotBlank(businessType)) {
        // if ("0".equals(businessType)) {
        // grNonValued = "x";
        // }
        // }
        // "+purchaseResultTableName+"
        // 删除最终采购结果表中本流程的所有结果
        //String deleteHistoryDataSql = "delete from " + purchaseResultTableName + " where mainid = ?";
        String deleteHistoryDataSql = "DELETE FROM e10_core_business."+purchaseResultTableName+"\n" +
                "WHERE "+purchaseResultTableName+".form_data_id = ? " +
                "\tAND "+purchaseResultTableName+".delete_type = 0\n" +
                "\tAND "+purchaseResultTableName+".tenant_key = 'tl2k2r96ty'";
        String poolname_nq = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        boolean deleteResult = rs.executeUpdate(deleteHistoryDataSql, poolname_nq, mainId);
        logger_af05a192.info(String.valueOf("deleteResult:" + deleteResult + ",deleteHistoryDataSql:" + deleteHistoryDataSql));
        String errorMessage;
        // 根据供应商代码和Purchase Org分组创建PO
//        String groupSupplierSql = "select gysdm,purchase_org,center_order from " + purchaseDetailTableName + " where mainid = ? group by gysdm,purchase_org";
        String groupSupplierSql = "SELECT "+purchaseDetailTableName+".gysdm AS gysdm, "+purchaseDetailTableName+".purchase_org AS purchase_org, center_order AS center_order\n" +
                "FROM e10_core_business."+purchaseDetailTableName+" " +
                "WHERE "+purchaseDetailTableName+".form_data_id = ? " +
                "\tAND "+purchaseDetailTableName+".delete_type = 0\n" +
                "\tAND "+purchaseDetailTableName+".tenant_key = 'tl2k2r96ty'\n" +
                "GROUP BY "+purchaseDetailTableName+".gysdm, "+purchaseDetailTableName+".purchase_org";
        logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",groupSupplierSql:" + groupSupplierSql));
        String poolname_fx = CONN_TYPE.workflow.getType();
        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
        rs.executeQuery(groupSupplierSql, poolname_fx, mainId);
        logger_af05a192.info(String.valueOf("Result Count:" + rs.getCounts()));
        // 遍历供应商，创建PO
        while (rs.next()) {
            String purchaseOrder = null;
            // 供应商代码
            String currentSupplierCode = Util.null2String(rs.getString("gysdm"));
            // center_order
            String currentCenterOrder = Util.null2String(rs.getString("center_order"));
            // purchase_org
            String currentPurchaseOrg = Util.null2String(rs.getString("purchase_org"));
            logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",currentSupplierCode:" + currentSupplierCode + ",currentCenterOrder:" + currentCenterOrder + ",currentPurchaseOrg:" + currentPurchaseOrg));
            long eitResultCount = 0L;
            String companyCode = null;
            String purchaseOrg = null;
            String purchaseGroup = null;
            String plant = null;
            String createdById = null;
            if (StringUtils.isNotBlank(currentPurchaseOrg)) {
                // 根据明细表1中的center_order，获取uf_EIT表业务数据
                RecordSet eitRS = I18nContextUtil.getBean(RecordSet.class);
                // queryEitSql = "select companycode,purchaseorg,purchasegroup,plant,poteam from uf_EIT where center_order = ?";
                String queryEitSql = "SELECT uf_EIT.companycode AS companycode, uf_EIT.purchaseorg AS purchaseorg, uf_EIT.purchasegroup AS purchasegroup, uf_EIT.plant AS plant, uf_EIT.poteam AS poteam\n" +
                        "FROM e10_common.uf_EIT\n" +
                        "WHERE uf_EIT.center_order = ?\n" +
                        "\tAND uf_eit.delete_type = 0\n" +
                        "\tAND uf_eit.tenant_key = 'tl2k2r96ty'";
                logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",queryEitSql:" + queryEitSql + ",center_order:" + currentCenterOrder));
                String poolname_2c = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                eitRS.executeQuery(queryEitSql, poolname_2c, currentCenterOrder);
                eitResultCount = eitRS.getCounts();
                if (eitRS.next()) {
                    companyCode = Util.null2String(eitRS.getString("companycode"));
                    purchaseOrg = Util.null2String(eitRS.getString("purchaseorg"));
                    purchaseGroup = Util.null2String(eitRS.getString("purchasegroup"));
                    plant = Util.null2String(eitRS.getString("plant"));
                    createdById = Util.null2String(eitRS.getString("poteam"));
                }
            }
            logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",Query Result -> eitResultCount:" + eitResultCount + ",companyCode:" + companyCode + ",purchaseOrg:" + purchaseOrg + ",purchaseGroup:" + purchaseGroup + ",createdById:" + createdById));
            // KBS/KTI Controller Team
            String kbs = null;
            // 如果明细表1中的center_order匹配到uf_EIT表中的数据，正常创建PO；否则，直接报错，终止创建PO
            if (eitResultCount > 0) {
                // 获取PO创建人networkId
                String networkId = null;
                if (StringUtils.isNotBlank(createdById)) {
                    RecordSet networkRS = I18nContextUtil.getBean(RecordSet.class);
                    // todo 后续改
                    //String queryNetworkIdSql = "select field15 from cus_fielddata where id = ? and scopeid = -1";
                    String queryNetworkIdSql = "select field15,eteams.employee.id from  eteams.hrmemployeedefined left join   eteams.employee  ON  eteams.hrmemployeedefined.form_data_id = eteams.employee.formdata\n" +
                            "where eteams.employee.id= ? ";
                    logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",queryNetworkIdSql:" + queryNetworkIdSql));
                    String poolname_o0 = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    networkRS.executeQuery(queryNetworkIdSql, poolname_o0, createdById);
                    if (networkRS.next()) {
                        networkId = Util.null2String(networkRS.getString("field15"));
                    }
                    logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",Query Result -> networkId:" + networkId));
                }
                RecordSet purchaseDtlRS = I18nContextUtil.getBean(RecordSet.class);
                //String purchaseDtlSql = "select id,msdhhao,sl,dw,gdzcbh,glaccount,accountassignment,xminternalorder,cbzxbh,cgcbj,bl,wlhz,itemmaterialtext,delivery_date,KBS from " + purchaseDetailTableName + " where mainid = ? and gysdm = ? and purchase_org = ?";
                String purchaseDtlSql = "SELECT "+purchaseDetailTableName+".id AS id, msdhhao AS msdhhao, sl AS sl, dw AS dw, gdzcbh AS gdzcbh\n" +
                        "\t, glaccount AS glaccount, accountassignment AS accountassignment, xminternalorder AS xminternalorder, cbzxbh AS cbzxbh, cgcbj AS cgcbj\n" +
                        "\t, bl AS bl, wlhz AS wlhz, itemmaterialtext AS itemmaterialtext, delivery_date AS delivery_date, "+purchaseDetailTableName+".kbs AS KBS\n" +
                        "FROM e10_core_business."+purchaseDetailTableName+"\n" +
                        "WHERE "+purchaseDetailTableName+".form_data_id = ?\n" +
                        "\tAND "+purchaseDetailTableName+".gysdm = ?\n" +
                        "\tAND "+purchaseDetailTableName+".purchase_org = ?\n" +
                        "\tAND "+purchaseDetailTableName+".delete_type = 0\n" +
                        "\tAND "+purchaseDetailTableName+".tenant_key = 'tl2k2r96ty'";
                logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",PurchaseDtlSql:" + purchaseDtlSql));
                String poolname_4g = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                purchaseDtlRS.executeQuery(purchaseDtlSql, poolname_4g, mainId, currentSupplierCode, currentPurchaseOrg);
                // 序号:初始值为0，每行递增10（例如：10，20,30）
                long detailId = 0L;
                // 描述/订货号
                String describeOrOrderNo = "";
                // 数量
                double quantity;
                // 单位
                String unit = "";
                // G/L Account
                String glAccount = "";
                // Account Assignment
                String accountAssignment = "";
                // 采购成本价（含税价）
                String grossPrice = "";
                // storage location
                String storageLocation = "";
                String internalOrder = "";
                // 成本中心编号
                String costCenterNo = "";
                // 固定资产编号
                String fixedAssetNo = "";
                // 发票税率
                String invoiceTaxRate;
                // 物料号
                String material = "";
                // 创建PO唯一标识，用于SAP防止重复创建PO
                String extProcessID = "BPM_" + requestId + "_" + currentSupplierCode.substring(2) + "_" + currentPurchaseOrg;
                // 交货日期
                String deliveryDate;
                PoHeader poHeader = new PoHeader();
                poHeader.setCompanyCode(companyCode);
                poHeader.setVendor(currentSupplierCode);
                if (StringUtils.isNotBlank(networkId)) {
                    poHeader.setCreatedBy(networkId);
                }
                poHeader.setPurchaseOrg(purchaseOrg);
                poHeader.setPurchaseGroup(purchaseGroup);
                // 获取币种名字
                String sql ="select currency_name from e10-base.i18n_currency  where id=?";
                rs2.executeQuery(sql,CONN_TYPE.workflow,currency);
                String currency_name ="";
                if(rs2.next()){
                    currency_name = rs2.getString("currency_name");
                }
               // poHeader.setCurrency(Currency.fromType(currency).getName());
                poHeader.setCurrency(currency_name);
                poHeader.setExtProcessID(extProcessID);
                List<PoItemAddress> poItemAddressList = new ArrayList<>();
                // 根据收货人ID查询收货人lastname
                if (StringUtils.isNotBlank(consigneeId)) {
                    List<HrmResourceInfo> hrmResourceInfoList = new ArrayList<>();
                    HrmResourceInfo hrmResourceInfo = new HrmResourceInfo();
                    hrmResourceInfo.setId(Long.parseLong(consigneeId));
                    hrmResourceInfoList.add(hrmResourceInfo);
                    List<HrmResourceInfo> resultList = PlatformCommonService.getUsersInfoBatch(hrmResourceInfoList);
                    if (!resultList.isEmpty()) {
                        consignee = resultList.get(0).getLastName();
                    }
                }
                PoItemAddress poItemAddress = new PoItemAddress();
                poItemAddress.setName3("联系人：" + consignee);
                poItemAddress.setCity(city);
                poItemAddress.setStreet("交货地址：" + deliveryAddress);
                poItemAddress.setTelephone("联系电话：" + consigneePhone);
                poItemAddressList.add(poItemAddress);
                PoAddress poAddress = null;
                List<PoHeaderText> poHeaderTextList = new ArrayList<>();
                PoHeaderText poHeaderText;
                // 如果vendor为KONEOTV,报文才送poAddress和poHeaderTexts
                if (currentSupplierCode.equals("KONEOTV")) {
                    poAddress = new PoAddress();
                    poAddress.setName(oneTimeSupplierName);
                    poAddress.setCity(city);
                    poAddress.setStreet(street);
                    poAddress.setCountry(country);
                    poAddress.setTelephone(telephone);
                    String[] bankInfoArray = bankInfo.split(";");
                    for (String item : bankInfoArray) {
                        if (StringUtils.isNotBlank(item)) {
                            poHeaderText = new PoHeaderText();
                            poHeaderText.setTextID("F01");
                            poHeaderText.setTextLine(item);
                            poHeaderTextList.add(poHeaderText);
                        }
                    }
                }
                // 将收货人、收货人联系方式、交货地址三个字段传到header text的delivery处
                if (StringUtils.isNotBlank(consignee)) {
                    poHeaderText = new PoHeaderText();
                    poHeaderText.setTextID("F14");
                    poHeaderText.setTextLine("联系人：" + consignee);
                    poHeaderTextList.add(poHeaderText);
                }
                if (StringUtils.isNotBlank(consigneePhone)) {
                    poHeaderText = new PoHeaderText();
                    poHeaderText.setTextID("F14");
                    poHeaderText.setTextLine("联系电话：" + consigneePhone);
                    poHeaderTextList.add(poHeaderText);
                }
                if (StringUtils.isNotBlank(deliveryAddress)) {
                    poHeaderText = new PoHeaderText();
                    poHeaderText.setTextID("F14");
                    poHeaderText.setTextLine("交货地址：" + deliveryAddress);
                    poHeaderTextList.add(poHeaderText);
                }
                List<PoItem> poItemList = new ArrayList<>();
                List<PoAccount> poAccountList = new ArrayList<>();
                List<PoCondition> poConditionList = new ArrayList<>();
                logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + "======According To Supplier Details Create PO Start======SupplierCode:" + currentSupplierCode));
                // 遍历供应商明细信息，拼报文
                while (purchaseDtlRS.next()) {
                    detailId += 10;
                    quantity = purchaseDtlRS.getDouble("sl");
                    unit = Util.null2String(purchaseDtlRS.getString("dw"));
                    accountAssignment = Util.null2String(purchaseDtlRS.getString("accountassignment"));
                    invoiceTaxRate = purchaseDtlRS.getString("bl");
                    glAccount = Util.null2String(purchaseDtlRS.getString("glaccount"));
                    grossPrice = Util.null2String(purchaseDtlRS.getString("cgcbj"));
                    describeOrOrderNo = Util.null2String(purchaseDtlRS.getString("msdhhao"));
                    internalOrder = Util.null2String(purchaseDtlRS.getString("xminternalorder"));
                    costCenterNo = Util.null2String(purchaseDtlRS.getString("cbzxbh"));
                    fixedAssetNo = Util.null2String(purchaseDtlRS.getString("gdzcbh"));
                    material = Util.null2String(purchaseDtlRS.getString("wlhz"));
                    deliveryDate = Util.null2String(purchaseDtlRS.getString("delivery_date"));
                    if (StringUtils.isBlank(kbs)) {
                        kbs = Util.null2String(purchaseDtlRS.getString("KBS"));
                    }
                    PoItem poItem = new PoItem();
                    PoAccount poAccount = new PoAccount();
                    PoCondition poCondition = new PoCondition();
                    poItem.setItemNumber(String.valueOf((int) detailId));
                    poItem.setPlant(plant);
                    poItem.setStorageLocation(storageLocation);
                    int processNoLength = processNo.length();
                    // 截取后10位流程编号
                    if (processNoLength >= 10) {
                        String departmentCode = processNo.substring(5, 8);
                        String processNoSuffix = processNo.substring(processNoLength - 7);
                        poItem.setRequirementTrackingNr(departmentCode + processNoSuffix);
                    }
                    poItem.setAcctAssCat(accountAssignment);
                    poItem.setMaterial(material);
                    poItem.setShortText(describeOrOrderNo);
                    // 如果物料号为空时默认为A，否则为空
                    if (StringUtils.isBlank(material)) {
                        poItem.setMaterialGroup("A");
                    }
                    // commercial
                    poItem.setQuantity(quantity);
                    // 单位转换
                    RecordSet unitRS = I18nContextUtil.getBean(RecordSet.class);
                    //String unitSql = "select unit from uf_dwzhb where commercial = ?";
                    String unitSql = "SELECT uf_dwzhb.unit AS unit\n" +
                            "FROM e10_common.uf_dwzhb\n" +
                            "WHERE uf_dwzhb.commercial = ?\n" +
                            "\tAND uf_dwzhb.delete_type = 0\n" +
                            "\tAND uf_dwzhb.tenant_key = 'tl2k2r96ty'";
                    logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",UnitSql:" + unitSql));
                    String poolname_w7 = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    unitRS.executeQuery(unitSql, poolname_w7, unit);
                    if (unitRS.next()) {
                        unit = Util.null2String(unitRS.getString("unit"));
                    }
                    poItem.setUnit(unit);
                    poItem.setPriceUnit(unit);
                    // poItem.setGrNonValuated(grNonValued);
                    /**
                     * 描述：
                     * 为了后续订单能够正确GRIR，BPM PR转PO中，除了房租物业和GSS订单外，其他所有PO生成后需要勾选SAP参数：GR-Bsd IV
                     * 1，供应商为GSS，PR-PO的时候，不勾选SAP参数：GR-Bsd IV
                     * 2，费用为房租物业类型，PR-PO的时候，不勾选SAP参数：GR-Bsd IV，建议可抓取房租物业的GL：436500&436980
                     * 3，其余订单，PR-PO的时候，勾选SAP参数：GR-Bsd IV
                     * 不打勾为空，打勾赋值x
                     */
                    String grBasedIV = "x";
                    if ((StringUtils.isNotBlank(glAccount) && rentPropertyGlAccountList.contains(glAccount)) || supplierGssCodeList.contains(currentSupplierCode)) {
                        grBasedIV = "";
                    }
                    poItem.setGrBasedIV(grBasedIV);
                    if (StringUtils.isNotBlank(grossPrice)) {
                        try {
                            poItem.setGrossPrice(new DecimalFormat().parse(grossPrice).doubleValue());
                        } catch (ParseException e) {
                            logger_af05a192.error(e.getMessage());
                            throw new RuntimeException(e);
                        }
                    }
                    if (StringUtils.isNotBlank(deliveryDate)) {
                        List<ScheduleLine> scheduleLineList = new ArrayList<>();
                        ScheduleLine scheduleLine = new ScheduleLine();
                        scheduleLine.setDeliveryDate(deliveryDate);
                        scheduleLine.setQuantity(quantity);
                        scheduleLineList.add(scheduleLine);
                        poItem.setScheduleLines(scheduleLineList);
                    }
                    poAccount.setItemNumber(String.valueOf((int) detailId));
                    poAccount.setGlAccount(glAccount);
                    switch(accountAssignment) {
                        case "F":
                            poAccount.setInternalOrder(internalOrder);
                            break;
                        case "K":
                            poAccount.setCostCenter(costCenterNo);
                            break;
                        case "A":
                            poAccount.setAssetNumber(fixedAssetNo);
                            break;
                        case "X":
                            poAccount.setCostCenter(costCenterNo);
                            poAccount.setInternalOrder(internalOrder);
                            break;
                        default:
                            break;
                    }
                    poCondition.setItemNumber(String.valueOf((int) detailId));
                    if (StringUtils.isNotBlank(invoiceTaxRate)) {
                        try {
                            poCondition.setCondValue(new DecimalFormat().parse(invoiceTaxRate).doubleValue());
                        } catch (ParseException e) {
                            logger_af05a192.error(e.getMessage());
                            throw new RuntimeException(e);
                        }
                    }
                    poItemList.add(poItem);
                    poAccountList.add(poAccount);
                    poConditionList.add(poCondition);
                }
                // 构造请求报文
                JsonMessageBuild jsonMessageBuild = new JsonMessageBuild();
                PoReqMessage poReqMessage = jsonMessageBuild.buildPoRequestMessage(poHeader, poAddress, poHeaderTextList, poItemList, null, poItemAddressList, poAccountList, poConditionList);
                // 调用创建PO接口
                Map<String, String> resultMap = sapCommonService.createPurchaseOrder(requestId, poReqMessage, createPoStatus, currentSupplierCode);
                errorMessage = resultMap.get("errorMessage");
                createPoStatus = resultMap.get("createPoStatus");
                purchaseOrder = resultMap.get("purchaseOrder");
            } else {
                // center_order匹配uf_EIT表业务数据失败提示
                errorMessage = "center_order信息匹配失败，请联系管理员！";
                createPoStatus = FAILURE_AND_CONTINUE;
            }
            RecordSet purchaseResultRS = I18nContextUtil.getBean(RecordSet.class);
            // 将PO创建结果记录到采购结果表中
            logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",Record The PO Create Result In The Purchase Result Table"));
            //String insertPurchaseResultSql = "insert into " + purchaseResultTableName + "(mainid,poh,gysdm,purchase_org,fhxx,KBS) values(?,?,?,?,?,?)";
            String insertPurchaseResultSql = "insert into " + purchaseResultTableName + " (id,form_data_id, poh, gysdm, purchase_org, fhxx\n" +
                    "\t, kbs,delete_type,tenant_key) values(?,?,?,?,?,?,?,?,?)";
            logger_af05a192.info(String.valueOf("insertPurchaseResultSql:" + insertPurchaseResultSql + ",KBS:" + kbs));
            String poolname_0t = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean insertResult = purchaseResultRS.executeUpdate(insertPurchaseResultSql, poolname_0t, IdGenerator.generate(),mainId, purchaseOrder, currentSupplierCode, currentPurchaseOrg, errorMessage, kbs,"0","tl2k2r96ty");
            logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",Insert " + purchaseResultTableName + " Table Status:" + insertResult));
            // 创建PO完成，开始上传附件
            if (StringUtils.isNotBlank(purchaseOrder)) {
                // 如果附件ID存在，上传PO附件；不存在上传附件结果直接赋值success
                if (StringUtils.isNotBlank(attachmentId)) {
                    errorMessage = sapCommonService.uploadAttachments(requestId, purchaseOrder, attachmentId);
                    if (!errorMessage.equals("success")) {
                        createPoStatus = FAILURE_AND_CONTINUE;
                    }
                } else {
                    logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",No Attachments Uploaded,Return Success"));
                    errorMessage = "success";
                }
                // 将上传附件的结果更新到采购结果表中
                logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",Record The Uploading Attachments Result In The Purchase Result Table"));
                RecordSet updateUploadResultRS = I18nContextUtil.getBean(RecordSet.class);
                //String updateSql = "update " + purchaseResultTableName + " set fhxx = ? where mainid = ? and gysdm = ? and purchase_org = ? and poh = ?";
                String updateSql = "update " + purchaseResultTableName + " set fhxx = ? where form_data_id = ? and gysdm = ? and purchase_org = ? and poh = ?  AND delete_type = 0 " +
                        " AND tenant_key = 'tl2k2r96ty' ";
                String poolname_gh = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean updateResult = updateUploadResultRS.executeUpdate(updateSql, poolname_gh, errorMessage, mainId, currentSupplierCode, currentPurchaseOrg, purchaseOrder);
                logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",Update " + purchaseResultTableName + " Table Status:" + updateResult));
            } else {
                logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",Create PO Failed, No Longer Uploading Attachments"));
            }
            logger_af05a192.info(String.valueOf("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + "======According To Supplier Details Create PO Complete======"));
        }
        logger_af05a192.info(String.valueOf("RequestId:" + requestId + "======Complete Create EIT PO======ReturnResult:" + createPoStatus));
        return WeaResult.success(getResultMapForAction(weaverResultMap, "result", createPoStatus, requestInfo.getRequestManager()));
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }


}
